<template>
  <div class="index">
    <van-tabs :active="activeNav" @change="changeTab">
      <van-tab v-for="(nav, index) in navList" :title="nav.name" :key="index"></van-tab>
    </van-tabs>

    <van-card v-for="(goods, index) in goodsList" :key="index" :num="goods.stock" :price="goods.price" :desc="goods.descript" :title="goods.name" :thumb="goods.imgUrl" @click="viewGoodsDetail(goods.id)" />
  </div>
</template>

<script>
import card from "@/components/card";
import utils from "@/utils/index.js";
export default {
  data() {
    return {
      goodsList: [],
      navList: [
        {
          name: "新品",
          sing: 1
        },
        {
          name: "热销",
          sing: 2
        },
        {
          name: "价格",
          sing: 3
        }
      ],
      id: 0,
      sing: 0,
      activeNav: 0
    };
  },
  components: {
    card
  },
  onLoad(options) {
    wx.setNavigationBarTitle({
      title: "分类"
    })
  },
  methods: {
    changeTab(event) {
      const index = event.mp.detail.index;
      if (index == 2 && this.sing == 3) {
        this.navList[index].sing = 4;
      } else if (index == 2 && this.sing == 4) {
        this.navList[index].sing = 3;
      }
      this.sing = this.navList[index].sing;
      this.getGoodsList();
    },
    viewGoodsDetail(id) {
      const url = "../goods/index?id=" + id;
      wx.navigateTo({ url });
    },
    getGoodsList() {
      this.goodsList = []
      // 获取热门商品
      this.$API
        .post(
          "categoryFirst/getGoodsListByCategoryId?categoryId=" +
          +this.id +
          "&sing=" +
          this.sing
        )
        .then(res => {

          let tmpGoodsList = res;
          this.goodsList = [];
          for (let i = 0; i < tmpGoodsList.length; i++) {
            const e = tmpGoodsList[i];
            let t = {
              id: e.id,
              stock: e.stock,
              price: utils.formatPrice(e.price),
              descript: e.descript,
              name: e.name,
              imgUrl: utils.fileMgrUrl + e.pic
            };
            this.goodsList.push(t);
          }
        });
    }
  },

  created() { },

  onLoad(options) {
    this.id = options.id;
    this.sing = 1;
    this.getGoodsList();
  }
};
</script>

<style>
swiper {
  height: 220px;
}
swiper-item > navigator > image {
  width: 100%;
}
</style>
